package com.qf.driver.service.impl;

import com.qf.common.constant.CommonConstant;
import com.qf.common.dto.DeviceDataDto;
import com.qf.common.dto.DeviceModelDto;
import com.qf.common.model.DeviceModelValue;
import com.qf.common.sdk.bean.MqttMessage;
import com.qf.common.utils.JsonUtil;
import com.qf.driver.service.MqttReciveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 千锋健哥
 */
@Service
@Slf4j
public class MqttReciveServiceImpl implements MqttReciveService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void reciveMessage(MqttMessage mqttMessage) {
        //判断消息对象不为空
        if (mqttMessage != null) {
            try {
                //获取消息的topic主题
                String topicName = mqttMessage.getMessageHeader().getMqttReceivedTopic();
                //判断通道如果是上报传感器数据的通道, 在这里进行处理
                if (topicName.contains("/qfjava/device/data")) {
                    //获取消息载荷, 也就是具体消息字符串内容
                    String payload = mqttMessage.getMessagePayload().getPayload();
                    DeviceDataDto deviceDataDto = JsonUtil.parseObject(payload, DeviceDataDto.class);
                    //解析消息内容
                    if (deviceDataDto != null) {
                        //封装dto
                        DeviceModelValue deviceModelValue = new DeviceModelValue();
                        deviceModelValue.setCreateTime(new Date());
                        deviceModelValue.setDevice(deviceDataDto.getDevice());
                        deviceModelValue.setTenant_id(deviceDataDto.getTenant_id());
                        deviceModelValue.setProduct_key(deviceDataDto.getProduct_key());
                        deviceModelValue.setData(deviceDataDto.getData());

                        //将dto发送到rabbitmq中, 消峰, 在data数据中心中接收并保存数据到mongodb中
                        rabbitTemplate.convertAndSend(CommonConstant.Rabbit.TOPIC_EXCHANGE_VALUE,
                                CommonConstant.Rabbit.ROUTING_DEVICE_VALUE_PREFIX + "data" ,
                                deviceModelValue);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("qf-driver-mqtt服务, MqttReciveServiceImpl实现类, 转换对象失败.");
            }

        } else {
            log.info("=========传感器上报的消息数据为空=========");
        }
    }

}
